package com.wosiliujing.learning.aspect;

import cn.hutool.core.util.StrUtil;
import com.wosiliujing.learning.annotation.Inner;
import com.wosiliujing.learning.constant.SecurityConstants;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: liujing
 * @date: 2019/5/21 15:13
 * @description:
 */
@Slf4j
@Aspect
@Component
@AllArgsConstructor
public class SecurityOauthInnerAspect implements Ordered {

    private final HttpServletRequest request;

    @SneakyThrows
    @Around("@annotation(inner)")
    public Object around(ProceedingJoinPoint point, Inner inner){
        String header = request.getHeader(SecurityConstants.FROM);
        if(inner.value()&&!StrUtil.equals(SecurityConstants.FROM_IN,header)){
            log.warn("无权限调用接口{}",point.getSignature().getName());
            throw new AccessDeniedException("无权限访问");
        }
        return point.proceed();
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 1;
    }
}
